package com.example.elderlycaresystem.controller;

import com.example.elderlycaresystem.dao.LoginRequest;
import com.example.elderlycaresystem.entity.User;
import com.example.elderlycaresystem.result.Result;
import com.example.elderlycaresystem.service.UserService;
import com.example.elderlycaresystem.util.JwtTokenUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    //用户登录
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody LoginRequest loginRequest) {
        try {
            // 验证用户名和密码
            User user = userService.login(loginRequest.getUsername(), loginRequest.getPassword());
            if (user != null) {
                // 生成JWT Token
                String token = JwtTokenUtil.generateToken(user.getId().toString(), user.getUserName());

                // 创建返回数据Map
                Map<String, Object> data = new HashMap<>();
                data.put("user", user);
                data.put("token", token);

                // 返回成功结果
                return Result.success(data);
            } else {
                return Result.error("用户名或密码错误");
            }
        } catch (Exception e) {
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    // 添加用户
    @PostMapping
    public Result<String> addUser(@RequestBody User user) {
        try {
            int result = userService.addUser(user);
            return result > 0 ? Result.success("添加成功") : Result.error("添加失败");
        } catch (Exception e) {
            return Result.error("添加过程中发生错误: " + e.getMessage());
        }
    }

    // 根据ID查询用户
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        User user = userService.getUserById(id);
        return user != null ? Result.success(user) : Result.error("用户不存在");
    }

    // 根据用户名查询用户
    @GetMapping(params = "username")
    public Result<User> getUserByUserName(@RequestParam String username) {
        User user = userService.getUserByUserName(username);
        return user != null ? Result.success(user) : Result.error("用户不存在");
    }

    // 查询所有用户
    @GetMapping
    public Result<List<User>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        return Result.success(users);
    }

    // 更新用户信息
    @PutMapping("/{id}")
    public Result<Map<String, Object>> updateUser(@PathVariable Long id, @RequestBody User user) {
        try {
            // 1. 参数校验
            if (id == null || user == null) {
                return Result.error("参数不能为空");
            }

            // 2. 确保请求体中的ID与路径中的ID一致
            user.setId(id);

            // 3. 验证必要字段
            if (user.getUserName() == null || user.getUserName().trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }
            if (user.getEmail() == null || user.getEmail().trim().isEmpty()) {
                return Result.error("邮箱不能为空");
            }

            // 4. 检查用户是否存在
            User existingUser = userService.getUserById(id);
            if (existingUser == null) {
                return Result.error("用户不存在");
            }

            // 5. 保留创建时间，设置更新时间
            user.setCreateTime(existingUser.getCreateTime());
            user.setUpdateTime(LocalDateTime.now());

            // 6. 执行更新操作
            int result = userService.updateUser(user);

            if (result > 0) {
                // 7. 更新成功后，返回更新后的用户信息
                User updatedUser = userService.getUserById(id);
                Map<String, Object> data = new HashMap<>();
                data.put("user", updatedUser);
                return Result.success(data);
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            // 8. 异常处理
            return Result.error("更新过程中发生错误: " + e.getMessage());
        }
    }

    // 根据ID删除用户
    @DeleteMapping("/{id}")
    public Result<String> deleteUserById(@PathVariable Long id) {
        try {
            int result = userService.deleteUserById(id);
            return result > 0 ? Result.success("删除成功") : Result.error("用户不存在");
        } catch (Exception e) {
            return Result.error("删除过程中发生错误: " + e.getMessage());
        }
    }

    // 根据邮箱查询用户
    @GetMapping(params = "email")
    public Result<User> getUserByEmail(@RequestParam String email) {
        User user = userService.getUserByEmail(email);
        return user != null ? Result.success(user) : Result.error("用户不存在");
    }
}